package com.wannengbang.cloudleader.homepage;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.IncomeListBean;
import com.wannengbang.cloudleader.bean.OrderFeeBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.homepage.adapter.ShareIncomeListNewAdapter;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.Dp2Px;
import com.wannengbang.cloudleader.utils.GsonUlits;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.MaterialHeader;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IncomeNewActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_list_money)
    TextView tvListMoney;
    @BindView(R.id.tv_today_money)
    TextView tvTodayMoney;
    @BindView(R.id.tv_yesterday_money)
    TextView tvYesterdayMoney;
    @BindView(R.id.tv_current_month)
    TextView tvCurrentMonth;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_select_money)
    TextView tvSelectMoney;
    @BindView(R.id.tv_income_type)
    TextView tvIncomeType;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.layout_title)
    LinearLayout layoutTitle;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.view_line)
    View viewLine;

    private IHomePageModel homePageModel;
    private String start_time;
    private String end_time;
    private int timeType = 1;
    private Calendar selectedDate;
    private TimePickerView pvCustomTime;
    private TextView tvStartTime;
    private TextView tvEndTime;

    private List<IncomeListBean.DataBean.ItemListBean> sharBeanList;
    private ShareIncomeListNewAdapter listAdapter;
    private int page = 1;
    private String cycleType;
    private String param;
    //    private ArrayList<String> optionsItems = new ArrayList<>();
    private int relation_type;
    private boolean isSetBar;
    private List<String> list;
    private int coordinate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_income_new);
        ButterKnife.bind(this);
        getImmersionBar().statusBarDarkFont(false).statusBarDarkFont(false, 0.2f).init();
        initView();
        initData();
    }

    int maker;
    int hb_operation_type;
    int agency;

    private void initView() {

        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);


        if (userInfoBean != null && userInfoBean.getData() != null) {
            //创客身份 1是 2否
            maker = userInfoBean.getData().getMaker();
//            红包版运营中心 1是 2否
            hb_operation_type = userInfoBean.getData().getHb_operation_type();
            //是否是机构 1是 2否
            agency = userInfoBean.getData().getAgency();

        }
        Intent intent = getIntent();
        cycleType = intent.getStringExtra("cycleType");
        param = intent.getStringExtra("param");
        relation_type = intent.getIntExtra("relation_type", 0);
        coordinate = intent.getIntExtra("coordinate", 0);
        String relation_name = intent.getStringExtra("relation_name");
        String lists = intent.getStringExtra("lists");


        list = GsonUlits.getListFromGson(lists);


        refreshLayout.setRefreshHeader(new MaterialHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);

        tvIncomeType.setText(relation_name);

        int height = (int) Dp2Px.dp2Px(219);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {   //设置标题的背景颜色
                    layoutTitle.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) 0, 243, 243, 243));
                    titleBar.setTitleColor(getResources().getColor(R.color.white));
                    titleBar.setLeftIcon(R.mipmap.ic_back_white);
                    getImmersionBar().statusBarDarkFont(false).statusBarDarkFont(false, 0.2f).init();
                    isSetBar = false;
                } else if (scrollY > 0 && scrollY <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) scrollY / height;
                    float alpha = (255 * scale);
                    layoutTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) alpha, 243, 243, 243));
                } else {    //滑动到banner下面设置普通颜色
                    if (!isSetBar) {
                        layoutTitle.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                        viewLine.setBackgroundColor(Color.argb((int) 255, 243, 243, 243));
                        titleBar.setTitleColor(getResources().getColor(R.color.text_color_2));
                        titleBar.setLeftIcon(R.mipmap.ic_back_black);
                        getImmersionBar().statusBarDarkFont(true).statusBarDarkFont(true, 0.2f).init();
                        isSetBar = true;
                    }
                }
            }
        });


    }


    public void initData() {
        homePageModel = new HomePageModelImpl();
        start_time = DateTimeUtil.format(new Date());
        end_time = DateTimeUtil.format(new Date());
        selectedDate = Calendar.getInstance();

        if ("all".equals(cycleType)) {
            start_time = param.replace(".", "-");
            end_time = DateTimeUtil.format(new Date());
        } else if ("date".equals(cycleType)) {
            start_time = param.replace(".", "-");
            end_time = start_time;
        } else if ("month".equals(cycleType)) {
            start_time = DateTimeUtil.getFirstDayOfMonth(param.replace(".", "-"));
            end_time = DateTimeUtil.getLastDayOfMonth(param.replace(".", "-"));
        }

//        tvSelectTime.setText(start_time + " 至 " + end_time);
        tvSelectTime.setText(end_time + " 至 " + end_time);

        sharBeanList = new ArrayList<>();
        listAdapter = new ShareIncomeListNewAdapter(sharBeanList);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        requestSharefliterSum();
        requestMoneyDetailIndexNew();
    }


    public void requestSharefliterSum() {
        homePageModel.requestSharefliterSumNew(new DataCallBack<OrderFeeBean>() {
            @Override
            public void onSuccessful(OrderFeeBean bean) {
                String total = NumberFormatUtils.formatTwoDecimal(bean.getData().getTotal() / 100);
                tvListMoney.setText(total);
                String today = NumberFormatUtils.formatTwoDecimal(bean.getData().getToday() / 100);
                tvTodayMoney.setText(today);
                String yesterday = NumberFormatUtils.formatTwoDecimal(bean.getData().getYesterday() / 100);
                tvYesterdayMoney.setText(yesterday);
                String month = NumberFormatUtils.formatTwoDecimal(bean.getData().getMonth() / 100);
                tvCurrentMonth.setText(month);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    int ip = 0;

    public void requestMoneyDetailIndexNew() {

        if (ip==0){
            start_time = end_time;
            ip++;
        }
        
        homePageModel.requestMoneyDetailIndexNew(page, relation_type + "", start_time, end_time, new DataCallBack<IncomeListBean>() {
            @Override
            public void onSuccessful(IncomeListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    sharBeanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (bean.getData().getTotal() != null) {
                    String total = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(bean.getData().getTotal().getMoney_count()) / 100);
                    tvSelectMoney.setText(total);
                }
                if (sharBeanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestMoneyDetailIndexNew();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        sharBeanList.clear();
        requestMoneyDetailIndexNew();
        requestSharefliterSum();
        refreshLayout.finishRefresh(30000);
    }

    private void showGsInfo() {
        // 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                coordinate = options1;
                String s1 = list.get(options1);
                //截取#之前的字符串
                String userIdJiequ = s1.substring(0, s1.indexOf("&"));
                //截取之后的字符
                String substring = s1.substring(s1.indexOf("&"));

                Log.e("字符串截取", userIdJiequ);
                Log.e("字符串截取", substring.replace("&", ""));
//
                relation_type = Integer.valueOf(substring.replace("&", ""));

                tvIncomeType.setText(userIdJiequ);

                refreshData();
            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(16)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(18)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();

        List<String> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            //截取#之前的字符串
            String userIdJiequ = list.get(i).substring(0, list.get(i).indexOf("&"));
            lists.add(userIdJiequ);
        }

        pvOptions.setPicker(lists);


        pvOptions.setSelectOptions(coordinate);


        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

    }

    @OnClick({R.id.tv_select_time, R.id.tv_income_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select_time:
                selectTime();
                break;
            case R.id.tv_income_type:
                showGsInfo();
                break;
        }
    }

    public void selectTime() {
        timeType = 1;
        String[] times = tvSelectTime.getText().toString().split(" 至 ");
        if (times != null) {
            start_time = times[0];
            end_time = times[1];
        }
        selectedDate.setTime(DateTimeUtil.parse(start_time));
        //这里可以更改参数，有好多类型
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        endDate.set(2099, 11, 31);
        pvCustomTime = new TimePickerBuilder(mActivity, (date, v) -> {
            tvSelectTime.setText(start_time + " 至 " + end_time);
            refreshData();

        }).setType(new boolean[]{true, true, true, false, false, false})
                .setTimeSelectChangeListener(date -> {
                    if (timeType == 1) {
                        start_time = DateTimeUtil.format(date);
                        if (tvStartTime != null) {
                            tvStartTime.setText(start_time);
                        }
                    } else {
                        end_time = DateTimeUtil.format(date);
                        if (tvEndTime != null) {
                            tvEndTime.setText(end_time);
                        }
                    }
                })
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        TextView ivCancel = v.findViewById(R.id.tv_cancel);
                        tvStartTime = v.findViewById(R.id.tv_start_time);
                        tvEndTime = v.findViewById(R.id.tv_end_time);
                        View viewLine1 = v.findViewById(R.id.view_line1);
                        View viewLine2 = v.findViewById(R.id.view_line2);
                        LinearLayout llStartTime = v.findViewById(R.id.ll_start_time);
                        LinearLayout llEndTime = v.findViewById(R.id.ll_end_time);

                        tvStartTime.setText(start_time);
                        tvEndTime.setText(end_time);

                        llStartTime.setOnClickListener(v1 -> {
                            timeType = 1;
                            tvStartTime.setTextColor(mActivity.getResources().getColor(R.color.theme_color));
                            viewLine1.setBackgroundColor(mActivity.getResources().getColor(R.color.theme_color));
                            tvEndTime.setTextColor(mActivity.getResources().getColor(R.color.text_color_2));
                            viewLine2.setBackgroundColor(mActivity.getResources().getColor(R.color.text_color_2));

                            selectedDate.setTime(DateTimeUtil.parse(tvStartTime.getText().toString()));
                            pvCustomTime.setDate(selectedDate);


                        });
                        llEndTime.setOnClickListener(v1 -> {
                            timeType = 2;
                            tvStartTime.setTextColor(mActivity.getResources().getColor(R.color.text_color_2));
                            viewLine1.setBackgroundColor(mActivity.getResources().getColor(R.color.text_color_2));
                            tvEndTime.setTextColor(mActivity.getResources().getColor(R.color.theme_color));
                            viewLine2.setBackgroundColor(mActivity.getResources().getColor(R.color.theme_color));

                            selectedDate.setTime(DateTimeUtil.parse(tvEndTime.getText().toString()));
                            pvCustomTime.setDate(selectedDate);


                        });

                        tvSubmit.setOnClickListener(v1 -> {
                            pvCustomTime.returnData();
                            pvCustomTime.dismiss();
                        });
                        ivCancel.setOnClickListener(v1 -> {
                            pvCustomTime.dismiss();
                        });
                    }
                })
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2f)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvCustomTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvCustomTime.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvCustomTime.show();
    }

}
